<template>
    <section>
        <el-dialog
                :title="user.id == 0 ? '添加农户' : '编辑农户' "
                :visible.sync="visible"
                :value="value"
                @close="close"
                width="800px"
        >
            <el-form
                    :model="user"
                    :inline="true"
                    :rules="rules"
                    ref="userForm"
            >
                <el-form-item
                        label="姓名"
                        :label-width="labelWidth"
                        prop="realName"
                >
                    <el-input
                            v-model="user.realName"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-vcard"
                            placeholder="请填写农户姓名"
                    />
                </el-form-item>
                <el-form-item
                        label="手机号码"
                        :label-width="labelWidth"
                        prop="mobile"
                >
                    <el-input
                            v-model="user.mobile"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-mobile"
                            placeholder="请填写农户手机号码"
                    />
                </el-form-item>
                <el-form-item
                        label="身份证号"
                        :label-width="labelWidth"
                        prop="idNo"
                >
                    <el-input
                            v-model="user.idNo"
                            auto-complete="off"
                            maxlength="18"
                            suffix-icon="fa fa-barcode"
                            placeholder="请填写农户身份证号"
                    />
                </el-form-item>
                <el-form-item
                        label="性别"
                        :label-width="labelWidth"
                        prop="sex"
                >
                    <el-select
                            v-model="user.sex"
                            placeholder="请选择性别"
                    >
                        <el-option
                                v-for="item in sexes"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item label="联系地址"
                              :label-width="labelWidth"
                              prop="address">
                    <el-cascader
                            :options="areas"
                            v-model="area"
                            placeholder="请选择区域信息"
                            @active-item-change="areaChange"
                    ></el-cascader>
                    <el-input
                            v-model="user.address"
                            auto-complete="off"
                            maxlength="128"
                            suffix-icon="fa fa-map-marker"
                            placeholder="请填写详细地址"
                    />
                </el-form-item>
                <el-form-item label="出生日期"
                              :label-width="labelWidth"
                              prop="birthDate">
                    <el-date-picker
                            v-model="user.birthDate"
                            align="left"
                            type="date"
                            size="small"
                            value-format="yyyy-MM-dd"
                            :clearable="false"
                            placeholder="选择日期" @change="calculateAge"
                            :picker-options="pickerOptions">
                    </el-date-picker>
                </el-form-item>
                <el-form-item
                        label="年龄"
                        :label-width="labelWidth"
                        prop="age"
                >
                    <el-input
                            v-model="user.age"
                            auto-complete="off"
                            maxlength="18"
                            disabled
                            suffix-icon="fa fa-modx"
                    />
                </el-form-item>
                <el-form-item
                        label="文化程度"
                        :label-width="labelWidth"
                        prop="diploma"
                >
                    <el-select
                            v-model="user.diploma"
                            placeholder="请选择文化程度"
                    >
                        <el-option
                                v-for="item in diplomas"
                                :key="item.value"
                                :label="item.name"
                                :value="item.value"
                        />
                    </el-select>
                </el-form-item>
                <!--<el-form-item-->
                <!--label="会员编号"-->
                <!--:label-width="labelWidth"-->
                <!--prop="vipCode"-->
                <!--&gt;-->
                <!--<el-input-->
                <!--v-model="user.vipCode"-->
                <!--auto-complete="off"-->
                <!--maxlength="32"-->
                <!--suffix-icon="fa fa-barcode"-->
                <!--placeholder="请填写农户会员编号"-->
                <!--/>-->
                <!--</el-form-item>-->
                <el-form-item
                        label="土地产权证编号"
                        :label-width="labelWidth"
                        prop="groundCertNo"
                >
                    <el-input
                            v-model="user.groundCertNo"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-barcode"
                            placeholder="请填写农户土地产权证编号"
                    />
                </el-form-item>
                <el-form-item
                        label="是否是贫困户"
                        :label-width="labelWidth"
                        prop="poorFlag"
                >
                    <el-select
                            v-model="user.poorFlag"
                            placeholder="请选择文化程度"
                    >
                        <el-option
                                v-for="item in poors"
                                :key="item.code"
                                :label="item.name"
                                :value="item.code"
                        />
                    </el-select>
                </el-form-item>
                <el-form-item
                        label="紧急联系人"
                        :label-width="labelWidth"
                        prop="emergencyContact"
                >
                    <el-input
                            v-model="user.emergencyContact"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-user-o"
                            placeholder="请填写农户紧急联系人"
                    />
                </el-form-item>
                <el-form-item
                        label="紧急联系人电话"
                        :label-width="labelWidth"
                        prop="emergencyContactPhone"
                >
                    <el-input
                            v-model="user.emergencyContactPhone"
                            auto-complete="off"
                            maxlength="11"
                            suffix-icon="fa fa-phone"
                            placeholder="请填写农户紧急联系人电话"
                    />
                </el-form-item>
                <el-form-item
                        label="银行卡号"
                        :label-width="labelWidth"
                        prop="bankNo"
                >
                    <el-input
                            v-model="user.bankNo"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-credit-card"
                            placeholder="请填写农户银行卡号"
                    />
                </el-form-item>
                <el-form-item
                        label="开户行"
                        :label-width="labelWidth"
                        prop="bankName"
                >
                    <el-input
                            v-model="user.bankName"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-university"
                            placeholder="请填写农户开户行"
                    />
                </el-form-item>
                <el-form-item
                        label="农资系数"
                        :label-width="labelWidth"
                        prop="factor"
                >
                    <el-input
                            v-model="user.factor"
                            auto-complete="off"
                            maxlength="32"
                            suffix-icon="fa fa-flag"
                            placeholder="请填写农户农资系数"
                    />
                </el-form-item>
                <el-form-item
                        label="合作社"
                        :label-width="labelWidth"
                        prop="cooperativeId"
                >
                    <el-select
                            v-model="user.cooperativeId"
                            placeholder="请选择合作社"
                    >
                        <el-option
                                v-for="item in cooperatives"
                                :key="item.id"
                                :label="item.name"
                                :value="item.id"
                        />
                    </el-select>
                </el-form-item>
            </el-form>
            <span
                    slot="footer"
                    class="dialog-footer"
            >
        <el-button
                size="small"
                @click="cancel('userForm')"
        >取 消</el-button>
        <el-button
                size="small"
                type="primary"
                @click="submit('userForm')"
        >确 定</el-button>
      </span>
        </el-dialog>
    </section>
</template>
<style>
</style>
<script>
    import {mapState} from "vuex";

    export default {
        name: "AddAndEdit",
        data() {
            var validAddress = (rule, value, callback) => {
                if (this.area.length < 5) {
                    callback(new Error("请选择联系地址的区域信息"));
                } else if (!value) {
                    callback(new Error("请填写详细地址"));
                } else {
                    callback();
                }
            };

            return {
                visible: false,
                labelWidth: "",
                sexes: [],
                areas: [],
                area: [],
                pickerOptions: {
                    disabledDate(time) {
                        return time.getTime() > Date.now();
                    }
                },
                user: {
                    id: 0,
                    mobile: "",
                    realName: '',
                    groundCertNo: '',
                    emergencyContact: '',
                    emergencyContactPhone: '',
                    bankNo: '',
                    bankName: '',
                    vipCode: '',
                    diploma: '',
                    poorFlag: false,
                    address: '',
                    idNo: '',
                    factor: 1,
                    cooperativeId: '',
                    cooperativeName: '',
                    birthDate: '',
                    age: 0
                },
                cooperatives: [],
                diplomas: [],
                poors: [{code: true, name: "是"}, {code: false, name: '否'}],
                rules: {
                    realName: [{required: true, message: "请输入姓名", trigger: "blur"}],
                    mobile: [{required: true, validator: this.$validator.mobile, trigger: "blur"}],
                    idNo: [{required: true, validator: this.$validator.idCardNo, trigger: "blur"}],
                    sex: [{required: true, message: "请选择性别", trigger: "blur"}],
                    address: [{required: true, validator: validAddress, trigger: "blur"}],
                    bankNo: [{required: false, validator: this.$validator.bankNo, trigger: "blur"}],
                    cooperativeId:[{required: true, message: "请选择合作社", trigger: "blur"}]
                }
            };
        },
        computed: {
            ...
                mapState({
                    codebooks: state => state.codebooks.codebooks
                })
        },
        watch: {
            value: {
                deep: true,
                immediate: true,
                handler:
                    function (val) {
                        this.visible = val.show;
                        this.labelWidth = val.formLabelWidth || "120px";
                        this.user = val.user;
                        this.user.factor = 1;
                        this.user.poorFlag = false;
                        if (this.visible) {
                            this.loadData();
                        }
                    }
            },
            visible(val) {
                if (!val) this.$emit("on-show-change", this.$data);
            }
        }
        ,
        mounted() {
            this.sexes = this.codebooks ? this.codebooks.sexs : [];
            this.diplomas = this.codebooks ? this.codebooks.diplomas : [];
            //获取合作社
            this.$api.cooperative.all(result => {
                this.cooperatives = result.cooperatives;
            })
            this.areaChange('');
        }
        ,
        methods: {
            close() {
                this.cancel('userForm');
            },
            cancel(formName) {
                this.$refs[formName].clearValidate();
                this.visible = false;
                this.user = {
                    id: 0
                };
                this.area = [];
            },
            calculateAge() {
                if (this.user.birthDate) {
                    let birthDate = new Date(this.user.birthDate).getFullYear();
                    let nowDate = new Date().getFullYear();
                    let age = nowDate - birthDate;
                    this.$set(this.user, "age", age);
                }
            },
            loadData() {
                if (!this.user || !this.user.id || this.user.id <= 0) {
                    return;
                }
                this.$api.farmer.detail(this.user.id, result => {
                    this.user = result.farmer;
                    this.user.sex = this.user.sex ? this.user.sex.value : "";
                    this.user.diploma = this.user.diploma ? this.user.diploma.value : "";
                    if (this.user.provinceCode && this.user.cityCode && this.user.countyCode && this.user.townCode && this.user.villageCode) {
                        this.area = [this.user.provinceCode, this.user.cityCode, this.user.countyCode, this.user.townCode, this.user.villageCode];
                        this.loadSaveArea(this.area, this.area.length);
                    }
                });
            }
            ,
            submit(formName) {
                this.$refs[formName].validate(valid => {
                    if (valid) {
                        const callback = () => {
                            this.cancel(formName);
                        };
                        this.cooperatives.forEach(item => {
                            if (item.id == this.user.cooperativeId) {
                                this.user.cooperativeName = item.name;
                            }
                        })
                        this.user.provinceCode = this.area[0];
                        this.user.cityCode = this.area[1];
                        this.user.countyCode = this.area[2];
                        this.user.townCode = this.area[3];
                        this.user.villageCode = this.area[4];
                        this.user.id
                            ? this.$api.farmer.update(this.user, callback)
                            : this.$api.farmer.save(this.user, callback);
                    } else {
                        return false;
                    }
                });
            },
            areaChange(val) {
                let parentCode = '';
                if (val) {
                    parentCode = val[val.length - 1];
                } else {
                    parentCode = val;
                }
                this.$api.common.getAreaByParentCode(parentCode, result => {
                    if (!val) {
                        this.areas = result.areas;
                    } else {
                        result.areas = result.areas.map(item => {
                            if (item.areaLevel.value === "VILLAGE") {
                                return {
                                    value: item.value,
                                    label: item.label,
                                    parentCode: item.parentCode,
                                    areaLevel: item.areaLevel
                                }
                            } else {
                                return item;
                            }
                        })
                        this.pickChild(this.areas, parentCode, result.areas, val.length);
                    }
                })
            },
            pickChild(orgArea, parentCode, childArea, deep) {
                if (orgArea) {
                    orgArea.forEach(item => {
                        if (item.value === parentCode && item.areaLevel.value != 'VILLAGE') {
                            item.children = childArea;
                        } else {
                            this.pickChild(item.children, parentCode, childArea, deep--);
                        }
                    });
                }
            },
            loadSaveArea(area, loop) {
                if (loop < 0) {
                    return;
                }
                let code = area[area.length - loop];
                this.$api.common.getAreaByParentCode(code, result => {
                    let child = result.areas.map(item => {
                        if (item.areaLevel.value === "VILLAGE") {
                            return {
                                value: item.value,
                                label: item.label,
                                parentCode: item.parentCode,
                                areaLevel: item.areaLevel
                            }
                        } else {
                            return item;
                        }
                    });
                    this.pickChild(
                        this.areas,
                        code,
                        child,
                        area - loop
                    );
                    loop--;
                    if (loop === 0) {
                        return;
                    }
                    this.loadSaveArea(area, loop);
                });
            }
        },
        props: {
            value: {
                type: Object,
                default:

                    function () {
                        return {
                            show: false,
                            formLabelWidth: "120px",
                            user: {
                                id: 0,
                                types: []
                            }
                        };
                    }
            }
        }
    };
</script>
